package com.bt.controller.user;

import com.bt.constant.JwtClaimsConstant;
import com.bt.dto.YUserLoginDTO;
import com.bt.entity.YddCate;
import com.bt.entity.YddUser;
import com.bt.properties.JwtProperties;
import com.bt.result.Result;
import com.bt.service.YddUserIndexService;
import com.bt.service.YddUserService;
import com.bt.utils.JwtUtil;
import io.jsonwebtoken.Jwt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author 张传康
 * @Date 2023-05-04 16:21
 */
@Slf4j
@Api(tags = "用户登录接口")
@RestController
@RequestMapping("/home/index")
public class YddUserLoginController {
    @Autowired
    private YddUserIndexService yddUserIndexService;
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 用户登录
     * @param yUserLoginDTO
     * @return
     */
    @ApiOperation("前台登录")
    @PostMapping("/login")
    public Result YddUserLogin(@RequestBody YUserLoginDTO yUserLoginDTO){
        // 前台传入的数据
        log.info("前台登录传入的数据是：{}",yUserLoginDTO);

        // 查询数据库是否存在该用户
        YddUser yddUser = yddUserIndexService.login(yUserLoginDTO);

        Map<String, Object> claims = new HashMap<>();
        // 设置 claims
        claims.put(JwtClaimsConstant.YDD_USER_ID, yddUser.getId());
        claims.put(JwtClaimsConstant.YDD_USERNAME, yddUser.getUsername());
        claims.put(JwtClaimsConstant.YDD_MOBILE, yddUser.getMobile());
        claims.put(JwtClaimsConstant.YDD_SEX, yddUser.getSex());
        claims.put(JwtClaimsConstant.YDD_PASSWORD, yddUser.getPassword());
        claims.put(JwtClaimsConstant.YDD_ICON,yddUser.getIcon());
        claims.put(JwtClaimsConstant.YDD_NOTES,yddUser.getNotes());
        claims.put(JwtClaimsConstant.YDD_BIRTHDAY, yddUser.getBirthday());
        claims.put(JwtClaimsConstant.YDD_ADDRESS, yddUser.getAddress());
        claims.put(JwtClaimsConstant.YDD_DEFAULT_DATA,yddUser.getDefaultData());

        // 设置密钥
        String token = JwtUtil.creteJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("token", token);



        return new Result<>("登录成功",map,0);
    }
}
